1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.collect;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20 import static com.google.common.base.Preconditions.checkNotNull;
21 import static com.google.common.collect.CollectPreconditions.checkNonnegative;
22 import static com.google.common.collect.CollectPreconditions.checkRemove;
23
24 import com.google.common.annotations.Beta;
25 import com.google.common.annotations.VisibleForTesting;
26 import com.google.common.collect.Serialization.FieldSetter;
27 import com.google.common.math.IntMath;
28 import com.google.common.primitives.Ints;
29
30 import java.io.IOException;
31 import java.io.ObjectInputStream;
32 import java.io.ObjectOutputStream;
33 import java.io.Serializable;
34 import java.util.Collection;
35 import java.util.Iterator;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.concurrent.ConcurrentHashMap;
40 import java.util.concurrent.ConcurrentMap;
41 import java.util.concurrent.atomic.AtomicInteger;
42
43 import javax.annotation.Nullable;
44
45
46
47
48
49
50
51
52
53
54
55
56
57 public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> implements Serializable {
58
59
60
61
62
63
64
65
66
67
68
69
70 private final transient ConcurrentMap<E, AtomicInteger> countMap;
71
72
73
74 private static class FieldSettersHolder {
75 static final FieldSetter<ConcurrentHashMultiset> COUNT_MAP_FIELD_SETTER =
76 Serialization.getFieldSetter(ConcurrentHashMultiset.class, "countMap");
77 }
78
79
80
81
82
83 public static <E> ConcurrentHashMultiset<E> create() {
84
85
86
87 return new ConcurrentHashMultiset<E>(new ConcurrentHashMap<E, AtomicInteger>());
88 }
89
90
91
92
93
94
95
96
97
98 public static <E> ConcurrentHashMultiset<E> create(Iterable<? extends E> elements) {
99 ConcurrentHashMultiset<E> multiset = ConcurrentHashMultiset.create();
100 Iterables.addAll(multiset, elements);
101 return multiset;
102 }
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125 @Beta
126 public static <E> ConcurrentHashMultiset<E> create(MapMaker mapMaker) {
127 return new ConcurrentHashMultiset<E>(mapMaker.<E, AtomicInteger>makeMap());
128 }
129
130
131
132
133
134
135
136
137
138
139
140 @VisibleForTesting ConcurrentHashMultiset(ConcurrentMap<E, AtomicInteger> countMap) {
141 checkArgument(countMap.isEmpty());
142 this.countMap = countMap;
143 }
144
145
146
147
148
149
150
151
152
153 @Override public int count(@Nullable Object element) {
154 AtomicInteger existingCounter = Maps.safeGet(countMap, element);
155 return (existingCounter == null) ? 0 : existingCounter.get();
156 }
157
158
159
160
161
162
163
164 @Override public int size() {
165 long sum = 0L;
166 for (AtomicInteger value : countMap.values()) {
167 sum += value.get();
168 }
169 return Ints.saturatedCast(sum);
170 }
171
172
173
174
175
176
177 @Override public Object[] toArray() {
178 return snapshot().toArray();
179 }
180
181 @Override public <T> T[] toArray(T[] array) {
182 return snapshot().toArray(array);
183 }
184
185
186
187
188
189 private List<E> snapshot() {
190 List<E> list = Lists.newArrayListWithExpectedSize(size());
191 for (Multiset.Entry<E> entry : entrySet()) {
192 E element = entry.getElement();
193 for (int i = entry.getCount(); i > 0; i--) {
194 list.add(element);
195 }
196 }
197 return list;
198 }
199
200
201
202
203
204
205
206
207
208
209
210
211 @Override public int add(E element, int occurrences) {
212 checkNotNull(element);
213 if (occurrences == 0) {
214 return count(element);
215 }
216 checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
217
218 while (true) {
219 AtomicInteger existingCounter = Maps.safeGet(countMap, element);
220 if (existingCounter == null) {
221 existingCounter = countMap.putIfAbsent(element, new AtomicInteger(occurrences));
222 if (existingCounter == null) {
223 return 0;
224 }
225
226 }
227
228 while (true) {
229 int oldValue = existingCounter.get();
230 if (oldValue != 0) {
231 try {
232 int newValue = IntMath.checkedAdd(oldValue, occurrences);
233 if (existingCounter.compareAndSet(oldValue, newValue)) {
234
235 return oldValue;
236 }
237 } catch (ArithmeticException overflow) {
238 throw new IllegalArgumentException("Overflow adding " + occurrences
239 + " occurrences to a count of " + oldValue);
240 }
241 } else {
242
243
244
245 AtomicInteger newCounter = new AtomicInteger(occurrences);
246 if ((countMap.putIfAbsent(element, newCounter) == null)
247 || countMap.replace(element, existingCounter, newCounter)) {
248 return 0;
249 }
250 break;
251 }
252 }
253
254
255 }
256 }
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276 @Override public int remove(@Nullable Object element, int occurrences) {
277 if (occurrences == 0) {
278 return count(element);
279 }
280 checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
281
282 AtomicInteger existingCounter = Maps.safeGet(countMap, element);
283 if (existingCounter == null) {
284 return 0;
285 }
286 while (true) {
287 int oldValue = existingCounter.get();
288 if (oldValue != 0) {
289 int newValue = Math.max(0, oldValue - occurrences);
290 if (existingCounter.compareAndSet(oldValue, newValue)) {
291 if (newValue == 0) {
292
293
294 countMap.remove(element, existingCounter);
295 }
296 return oldValue;
297 }
298 } else {
299 return 0;
300 }
301 }
302 }
303
304
305
306
307
308
309
310
311
312
313
314
315 public boolean removeExactly(@Nullable Object element, int occurrences) {
316 if (occurrences == 0) {
317 return true;
318 }
319 checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
320
321 AtomicInteger existingCounter = Maps.safeGet(countMap, element);
322 if (existingCounter == null) {
323 return false;
324 }
325 while (true) {
326 int oldValue = existingCounter.get();
327 if (oldValue < occurrences) {
328 return false;
329 }
330 int newValue = oldValue - occurrences;
331 if (existingCounter.compareAndSet(oldValue, newValue)) {
332 if (newValue == 0) {
333
334
335 countMap.remove(element, existingCounter);
336 }
337 return true;
338 }
339 }
340 }
341
342
343
344
345
346
347
348
349 @Override public int setCount(E element, int count) {
350 checkNotNull(element);
351 checkNonnegative(count, "count");
352 while (true) {
353 AtomicInteger existingCounter = Maps.safeGet(countMap, element);
354 if (existingCounter == null) {
355 if (count == 0) {
356 return 0;
357 } else {
358 existingCounter = countMap.putIfAbsent(element, new AtomicInteger(count));
359 if (existingCounter == null) {
360 return 0;
361 }
362
363 }
364 }
365
366 while (true) {
367 int oldValue = existingCounter.get();
368 if (oldValue == 0) {
369 if (count == 0) {
370 return 0;
371 } else {
372 AtomicInteger newCounter = new AtomicInteger(count);
373 if ((countMap.putIfAbsent(element, newCounter) == null)
374 || countMap.replace(element, existingCounter, newCounter)) {
375 return 0;
376 }
377 }
378 break;
379 } else {
380 if (existingCounter.compareAndSet(oldValue, count)) {
381 if (count == 0) {
382
383
384 countMap.remove(element, existingCounter);
385 }
386 return oldValue;
387 }
388 }
389 }
390 }
391 }
392
393
394
395
396
397
398
399
400
401
402
403
404 @Override public boolean setCount(E element, int expectedOldCount, int newCount) {
405 checkNotNull(element);
406 checkNonnegative(expectedOldCount, "oldCount");
407 checkNonnegative(newCount, "newCount");
408
409 AtomicInteger existingCounter = Maps.safeGet(countMap, element);
410 if (existingCounter == null) {
411 if (expectedOldCount != 0) {
412 return false;
413 } else if (newCount == 0) {
414 return true;
415 } else {
416
417 return countMap.putIfAbsent(element, new AtomicInteger(newCount)) == null;
418 }
419 }
420 int oldValue = existingCounter.get();
421 if (oldValue == expectedOldCount) {
422 if (oldValue == 0) {
423 if (newCount == 0) {
424
425 countMap.remove(element, existingCounter);
426 return true;
427 } else {
428 AtomicInteger newCounter = new AtomicInteger(newCount);
429 return (countMap.putIfAbsent(element, newCounter) == null)
430 || countMap.replace(element, existingCounter, newCounter);
431 }
432 } else {
433 if (existingCounter.compareAndSet(oldValue, newCount)) {
434 if (newCount == 0) {
435
436
437 countMap.remove(element, existingCounter);
438 }
439 return true;
440 }
441 }
442 }
443 return false;
444 }
445
446
447
448 @Override Set<E> createElementSet() {
449 final Set<E> delegate = countMap.keySet();
450 return new ForwardingSet<E>() {
451 @Override protected Set<E> delegate() {
452 return delegate;
453 }
454
455 @Override
456 public boolean contains(@Nullable Object object) {
457 return object != null && Collections2.safeContains(delegate, object);
458 }
459
460 @Override
461 public boolean containsAll(Collection<?> collection) {
462 return standardContainsAll(collection);
463 }
464
465 @Override public boolean remove(Object object) {
466 return object != null && Collections2.safeRemove(delegate, object);
467 }
468
469 @Override public boolean removeAll(Collection<?> c) {
470 return standardRemoveAll(c);
471 }
472 };
473 }
474
475 @Override public Set<Multiset.Entry<E>> createEntrySet() {
476 return new EntrySet();
477 }
478
479 @Override int distinctElements() {
480 return countMap.size();
481 }
482
483 @Override public boolean isEmpty() {
484 return countMap.isEmpty();
485 }
486
487 @Override Iterator<Entry<E>> entryIterator() {
488
489
490 final Iterator<Entry<E>> readOnlyIterator =
491 new AbstractIterator<Entry<E>>() {
492 private Iterator<Map.Entry<E, AtomicInteger>> mapEntries = countMap.entrySet().iterator();
493
494 @Override protected Entry<E> computeNext() {
495 while (true) {
496 if (!mapEntries.hasNext()) {
497 return endOfData();
498 }
499 Map.Entry<E, AtomicInteger> mapEntry = mapEntries.next();
500 int count = mapEntry.getValue().get();
501 if (count != 0) {
502 return Multisets.immutableEntry(mapEntry.getKey(), count);
503 }
504 }
505 }
506 };
507
508 return new ForwardingIterator<Entry<E>>() {
509 private Entry<E> last;
510
511 @Override protected Iterator<Entry<E>> delegate() {
512 return readOnlyIterator;
513 }
514
515 @Override public Entry<E> next() {
516 last = super.next();
517 return last;
518 }
519
520 @Override public void remove() {
521 checkRemove(last != null);
522 ConcurrentHashMultiset.this.setCount(last.getElement(), 0);
523 last = null;
524 }
525 };
526 }
527
528 @Override public void clear() {
529 countMap.clear();
530 }
531
532 private class EntrySet extends AbstractMultiset<E>.EntrySet {
533 @Override ConcurrentHashMultiset<E> multiset() {
534 return ConcurrentHashMultiset.this;
535 }
536
537
538
539
540
541
542 @Override public Object[] toArray() {
543 return snapshot().toArray();
544 }
545
546 @Override public <T> T[] toArray(T[] array) {
547 return snapshot().toArray(array);
548 }
549
550 private List<Multiset.Entry<E>> snapshot() {
551 List<Multiset.Entry<E>> list = Lists.newArrayListWithExpectedSize(size());
552
553 Iterators.addAll(list, iterator());
554 return list;
555 }
556 }
557
558
559
560
561 private void writeObject(ObjectOutputStream stream) throws IOException {
562 stream.defaultWriteObject();
563 stream.writeObject(countMap);
564 }
565
566 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
567 stream.defaultReadObject();
568 @SuppressWarnings("unchecked")
569 ConcurrentMap<E, Integer> deserializedCountMap =
570 (ConcurrentMap<E, Integer>) stream.readObject();
571 FieldSettersHolder.COUNT_MAP_FIELD_SETTER.set(this, deserializedCountMap);
572 }
573
574 private static final long serialVersionUID = 1;
575 }